﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace MobileServer
{
    class Program
    {
        static void Main(string[] args)
        {
            MobileServer();
            
        }

        private static void MobileServer()
        {
            int port = 1819;
            IPEndPoint remoteServer = new IPEndPoint(IPAddress.Parse("10.9.146.31"), 1818);

            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, port);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            try
            {
                socket.Bind(localEP);

                Console.WriteLine("手机通讯服务器启动了....");

                //while (true)
                //{
                    byte[] data = new byte[1024];
                    EndPoint clientIpe = (EndPoint)remoteServer;
                    int recv = socket.ReceiveFrom(data, ref clientIpe);

                    Console.WriteLine("从手机：" + clientIpe.ToString() + "接受到了数据.");
                    if (recv > 0)
                    {
                        string msg = Encoding.UTF8.GetString(data, 0, recv);
                        Console.WriteLine("数据是：" + msg);

                        IPEndPoint TcplocalEP = new IPEndPoint(IPAddress.Any, port);
                        Socket listener = new Socket(localEP.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                        listener.Bind(TcplocalEP);
                        listener.Connect(remoteServer);
                        listener.Send(Encoding.UTF8.GetBytes(msg));
                        Console.WriteLine("把数据转发至WebSocket通讯服务器");
                    }
                //}
                    Console.Read();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}
